package org.example.base.common.controller;

import com.alibaba.fastjson2.JSONObject;
import org.example.base.common.model.UserModel;
import org.example.base.common.service.UserService;
import org.example.core.controller.BaseController;
import org.example.core.enums.ApiResult;
import org.example.core.exception.ErrorException;
import org.example.core.mysql.SearchPageResult;
import org.example.core.mysql.Where;
import org.example.pingkunsheng.model.TTuitionWaiverModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<String, UserService, UserModel> {

    @Autowired
    private UserService userService;

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public ApiResult info() {
        return ApiResult.success(userService.getUserInfo());
    }

    @PostMapping("/addRoles")
    public ApiResult addRoles(@RequestBody Map<String, Object> params) {
        Object roleIds = params.get("roleIds");
        if (ObjectUtils.isEmpty(roleIds)){
            throw new ErrorException("roleIds不能为空");
        }
        String userId = getUserId();
        if (ObjectUtils.isEmpty(userId)){
            throw new ErrorException("userId不能为空");
        }
        userService.addRoles(params);
        return ApiResult.success();
    }

    @GetMapping("/getDetail")
    public ApiResult getDetail(String id){
        JSONObject userModelJsonObject = userService.getDetail(id);
        return ApiResult.success(userModelJsonObject);
    }

    @Override
    public ApiResult searchPage(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int limit,@RequestParam(required = false) Map<String, Object> params) {
        SearchPageResult<UserModel> result = new SearchPageResult<>();
        Object name = params.get("name");
        Where where  = Where.build().field("del_flag").equal(0);
        if (!ObjectUtils.isEmpty(name)){
            where.and().field("name").equal(name);
        }
        int totalCount = userService.count(where);
        List<UserModel> resultList = userService.search(where.limit(page, limit));
        result.setPage(page);
        result.setLimit(limit);
        result.setTotalCount(totalCount);
        result.setList(resultList);
        return ApiResult.success(result);
    }
}
